package com.oguzhan.xtools.soa.token.util;

import java.io.FileInputStream;
import java.util.LinkedList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;

import com.oguzhan.xtools.soa.token.ConfigurationType;
import com.oguzhan.xtools.soa.token.EnvironmentConfigType;


public class Config {

	private List<EnvironmentConfig> envConfigs;
	
	private Config() {	
		envConfigs = new LinkedList<EnvironmentConfig>();
	}
	
	protected void addEnvironmentConfig(EnvironmentConfig envCfg) {
		envConfigs.add(envCfg);
	}
	
	protected void removeEnvironmentConfig(EnvironmentConfig envCfg) {
		envConfigs.remove(envCfg);
	}
	
	public EnvironmentConfig getEnvironmentConfig(String environment) {
		for (EnvironmentConfig config : this.envConfigs) {
			if (config.getName().equals(environment)) {
				return config;
			}
		}
		
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static Config createConfig() {
		Config config = new Config();
		try {
			JAXBContext ctx = JAXBContext.newInstance( "tr.com.oguzhan.soa.security.token" );
			Unmarshaller unmarshaller = ctx.createUnmarshaller();
			JAXBElement<ConfigurationType> jaxbElement = (JAXBElement<ConfigurationType>) unmarshaller.unmarshal(new FileInputStream("configuration.xml"));
			ConfigurationType configType = jaxbElement.getValue();
			List<EnvironmentConfigType> environmentConfigTypes = configType.getEnvironments();
			for (EnvironmentConfigType environmentConfigType : environmentConfigTypes) {
				EnvironmentConfig environmentConfig = new EnvironmentConfig();
				environmentConfig.setName(environmentConfigType.getName());
				environmentConfig.setPassword(environmentConfigType.getPassword());
				environmentConfig.setUrl(environmentConfigType.getUrl());
				environmentConfig.setUser(environmentConfigType.getUser());
				config.addEnvironmentConfig(environmentConfig);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return config;
	}
}
